<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Selforder extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json_encode(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }

    }


    /**
     * getAttrById
     * 为老汤
     */
    public function getAttrById()
    {
        extract(input());
        $data = Db::table('up_self_goods_attr')
            ->where('sign_id',$attr_id)
            ->where('goods_id',$good_id)
            ->where('is_delete',0)
            ->find();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * getAttrById
     * 为老汤
     */
    public function getAttrByIdFor()
    {
        extract(input());
        $data = Db::table('up_goods')
            ->where('good_id',$good_id)
            ->find();
        $data['sign_str'] = $data['good_color'] . '/' . 1000;
        return json(['status'=>200,'msg'=>1000]);
    }
    /**
     * myOrderNums
     * 我的页面的订单数量
     * contract：1是自营  2是增补
     */
    public function myOrderNums()
    {
        extract(input());
        $data = $this->formyOrderNums($user_id,1);
        $data2 = $this->formyOrderNums($user_id,2);
        return json(['status'=>200,'msg'=>$data,'msg2'=>$data2]);
    }
    /**
     * myOrderNums
     * 我的页面的订单数量
     * contract：1是自营  2是增补
     */
    public function formyOrderNums($user_id,$contract)
    {
        extract(input());
        $where = [
            'user_id' => $user_id,
            'order_contract' => $contract,
            'o.is_delete' => 0
        ];
        if($contract != 1){
            $can = $this->getSonByUser($user_id);
            if($can['status'] != 200){
                return json_encode($can);
            }
            $sondata = $can['msg'];
            $where = [
                'order_user_son_id' => $sondata['uson_id'],
                'order_contract' => $contract,
                'o.is_delete' => 0
            ];
        }
        $where1 = [ //待付款
            'is_pay' => 0,
        ];
        $where2 = [ //待发货
            'is_pay' => 1,
            'is_send' => 0
        ];
        $where3 = [ //待收货
            'is_pay' => 1,
            'is_send' => 1
        ];
        $where4 = [ //待评价
            'is_pay' => 1,
            'is_send' => 2,
            'sale_status' => 0,
        ];
        $data = array();
        $data['nopay'] = Db::table('up_self_order')
            ->where($where)
            ->where($where1)
            ->count();
        $data['nosend'] = Db::table('up_self_order')
            ->where($where)
            ->where($where2)
            ->count();
        $data['noget'] = Db::table('up_self_order')
            ->where($where)
            ->where($where3)
            ->count();
        $data['nocomment'] = Db::table('up_self_order')
            ->where($where)
            ->where($where4)
            ->count();

        return $data;
    }
    /**
     * 我的订单
     * type：1待付款 2是待发货 3是待收货 4是已收货待评价 5是已完成
     * contract：1是自营  2是增补  3是统购
     */
    public function myOrders()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $where = [
            'user_id' => $user_id,
            'order_contract' => $contract,
            'o.is_delete' => 0
        ];
        if(!isset($contract)){
            $contract = 1;
        }
        $good_table = 'up_self_goods';
        if($contract != 1){
            $can = $this->getSonByUser($user_id);
            if($can['status'] != 200){
                return json_encode($can);
            }
            $sondata = $can['msg'];
            $where = [
                'order_user_son_id' => $sondata['uson_id'],
                'order_contract' => $contract,
                'o.is_delete' => 0
            ];
            $good_table = 'up_goods';
        }
        if(isset($type) && $type){
            if($type == 1){
                $where['is_pay'] = 0;
            }else{
                $where['is_pay'] = 1;
                if($type == 2){
                    $where['is_send'] = 0;
                }
                if($type == 3){
                    $where['is_send'] = 1;
                }
                if($type == 4){
                    $where['is_send'] = 2;
                    $where['sale_status'] = 0;
                }
                if($type == 5){
                    $where['is_send'] = 3;
                }
            }
        }
        //
        $field = 'o.order_id,o.is_sale,order_no,total_price,is_pay,is_send,sale_status,tui_status,order_cancel_status';
        $order = Db::table('up_self_order')->alias('o')
//            ->join('up_self_order_detail od','o.order_id=od.order_id','LEFT')
//            ->join('up_self_goods g','od.goods_id=g.good_id','LEFT')
            ->where($where)
            ->order('o.created_at desc')
            ->page($page,10)
            ->field($field)
            ->select();
        if($order){
            foreach ($order as $k=>$v){
                if($contract == 3){
                    $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,detail_id';//原先的
                    $field = 'oc_id,oc_num,oc_price,oc_size,oc_name,oc_image,oc_goods_info';
                    $details = Db::table('up_self_order_contract')
                        ->where('oc_order_id',$v['order_id'])
                        ->field($field)
                        ->select();
                    $order[$k]['goods'] = $details;
                    $order[$k]['count_num'] = count($details);
                }else{
                    $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,detail_id';
                    $details = Db::table('up_self_order_detail')->alias('od')
                        ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
                        ->where('order_id',$v['order_id'])
                        ->field($field)
                        ->select();
                    $order[$k]['goods'] = $details;
                    $order[$k]['count_num'] = count($details);
                }

            }
        }
        return json(['status'=>200,'msg'=>$order]);
    }
    /**
     * 我的某一个订单详情
     */
    public function myOrderInfo()
    {
        extract(input());
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        $where = [
            'od.order_id' => $order_id
        ];
        if(isset($tui) && $tui == 1){
            $where['od.refund_status'] = 0; //未售后的，售后结束的不能再次售后
        }
        $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,th_status,refund_status,detail_id,detail_express,detail_express_no';
        $good_table = 'up_self_goods';
        if($order['order_contract'] != 1){
            $good_table = 'up_goods';
            $field .= ',good_color';
//            $field .= ',good_90,good_100,good_110,good_120,good_130,good_140,good_150,good_155,good_160,good_165,good_170,good_175,good_180,good_185,good_190,good_195,good_200';
        }
        $field .= ',status';
        //----------------------先排查一下老用户的goods_id问题----------------------------
        $details = Db::table('up_self_order_detail')->alias('od')
            ->where($where)
            ->field('cloth_code,goods_id,detail_id')
            ->select();
        foreach ($details as $k => $v){
            if($v['goods_id'] <= 0){
                $newgoodcode = Db::table('up_z_new_old_img')->where('old',$v['cloth_code'])->value('new');
                $changegoods_id = Db::table('up_goods')->where('good_coding',$newgoodcode)->value('good_id');
                if($changegoods_id){
                    Db::table('up_self_order_detail')->alias('od')
                        ->where('detail_id',$v['detail_id'])
                        ->setField('goods_id',$changegoods_id);
                }
            }
        }
        //--------------------------------------------------
        $details = Db::table('up_self_order_detail')->alias('od')
            ->join("up_self_order_tui t",'od.detail_id=t.order_detail_id','LEFT')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where($where)
            ->field($field)
            ->select();
//
        $edit_size = 0;
        $sondata = [];
        if($order['order_contract'] != 1){
            $can = $this->getSonByUser($user_id);
            if($can['status'] != 200){
                return json_encode($can);
            }
            $sondata = $can['msg'];
            $time = time();
            $hours = Db::table('up_about')->where('id',9)->value('content');
            $hours = (int)$hours;
            $pay_time_24 = strtotime($order['pay_time']) + 3600*$hours;
            if($order['is_pay'] == 1 && $order['is_send'] == 0 && $pay_time_24 >= $time){
                $edit_size = 1;
            }
        }
//
        $wldata = [];
        if(count($details) <= 1){
            $wldata = orderWuLiu($details[0]['detail_express_no']);
            if($wldata['status'] == 200){
                $wldata['time'] = $wldata['msg'][0]['time'];
                $wldata['msg'] = $wldata['msg'][0]['context'];
            }
        }
        return json(['status'=>200,'msg'=>$order,'goods'=>$details,'count_num' => count($details),'sondata' => $sondata,'edit_size' => $edit_size,'wldata' => $wldata]);
    }
    public function getSizes()
    {
        $good_id = $_POST['good_id'];
        //获取尺寸
        $sizes = Db::table('up_good_spec')
            ->where('spec_good_id',$good_id)
            ->where('spec_size_type',1)
            ->group('spec_size')
            ->column('spec_size');
        return json(['status'=>200,'msg'=>$sizes]);
    }
    /**
     * msg：订单快递公司和单号、缩略图
     * wldata：
     *      status为200时展示快递信息，其他值时不展示，只展示里面的msg即可
     *      msg为物流信息数组
     *      wlstate为快递单当前状态，0在途，1揽收，2疑难，3签收，4退签，5派件，6退回
     */
    public function getWlInfo()
    {
        extract(input());
        $order_id = Db::table('up_self_order_detail')->where('detail_id',$detail_id)->value('order_id');
        $order_contract = Db::table('up_self_order')->where('order_id',$order_id)->value('order_contract');
        $good_table = 'up_self_goods';
        if($order_contract != 1){
            $good_table = 'up_goods';
        }
        $data = Db::table('up_self_order_detail')->alias('od')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where('detail_id',$detail_id)
            ->field('detail_express,detail_express_no,good_thumb')
            ->find();
        $wldata = orderWuLiu($data['detail_express_no']);
        if($wldata['status'] != 200){
            $wldata['msg'] = [];
        }
        return json(['status'=>200,'msg'=>$data,'wldata'=>$wldata]);
    }
    /**
     * 修改尺码
     */
    public function changeSize()
    {
        extract(input());
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        if($order['order_contract'] == 1) {
            return json(['status'=>0,'msg'=>'只有增补订单才可以修改尺码']);
        }
        $time = time();
        $hours = Db::table('up_about')->where('id',9)->value('content');
        $hours = (int)$hours;
        $pay_time_24 = strtotime($order['pay_time']) + 3600*$hours;
        if($order['is_pay'] == 1 && $order['is_send'] == 0 && $pay_time_24 >= $time){
            $changes = json_decode($changes,true);
            Db::startTrans();
            try{
                $sondata = Db::table('up_u_user_son')->where('uson_id',$order['order_user_son_id'])
                    ->field('uson_id,uson_username,user_gender,uson_year,uson_school,uson_idcard,uson_size')
                    ->find();
                foreach ($changes as $k=>$v){
                    $old = Db::table('up_self_order_detail')
                        ->where('detail_id',$v['detail_id'])
                        ->field('attr_id,goods_id,num,pay_year')
                        ->find();
                    if($v['attr_id'] != $old['attr_id']){
                        $o_g = Db::table('up_goods')
                            ->where('good_id',$old['goods_id'])
                            ->field("good_name,good_color,good_coding_less")
                            ->find();
                        //>>>>>>>>>>>>>>>>>>>获取唯一编码start>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                        $less_code = Db::table('up_good_spec')
                            ->where('spec_good_coding_less', $o_g['good_coding_less'])
                            ->where('spec_size', $v['attr_id'])
                            ->where('spec_size_q', 2)
                            ->value('spec_good_coding_less');
                        if ($less_code) { //说明此款号有Q款，再去判断
                            $erp = 2;
                        } else {
                            $erp = 1;//压根没有Q款
                        }
                        $sure = $this->getStudentGoods($sondata['uson_school'], $old['pay_year'], $sondata['user_gender'], $erp, $o_g['good_coding_less']);
                        $size_code = Db::table('up_good_spec')
                            ->where('spec_good_coding_less', $o_g['good_coding_less'])
                            ->where('spec_size', $v['attr_id'])
                            ->where('spec_size_q', $sure['sg_good_q'])
                            ->value('spec_size_two');
                        if(empty($size_code)){
                            Db::rollback();
                            return json_encode(['status'=>0,'msg'=>'尺码有误，请刷新重试，或重新选择尺码~']);
                        }
                        $unique_code = $sure['sg_good_coding'] . $size_code;
                        if ($sure['sg_sign']) {
                            $unique_code .= $sure['sg_sign'];
                        }
                        //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<获取唯一编码end<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                        Db::table('up_self_order_detail')->where('detail_id',$v['detail_id'])->update([
                            'goods_coding_unique' => $unique_code,
                            'attr_id' => $v['attr_id'],
                            'goods_info' => $o_g['good_color'] . '/' . $v['attr_id']
                        ]);
                    }
                }
                Db::commit();
                return json(['status'=>200,'msg'=>'修改成功！']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['status'=>0,'msg'=>'修改失败！']);
            }
        }else{
            return json(['status'=>0,'msg'=>'已发货或已超过调换时间范围，不可修改！']);
        }

    }
    /**
     * 手动取消订单
     *
     */
    public function cancleOrder()
    {
        extract(input());
        $is_pay = Db::table('up_self_order')->where('order_id', $order_id)->value('is_pay');
        if($is_pay != 0){
            return json_encode(['status'=>0,'msg'=>'只有未支付订单才可以取消']);
        }
        $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
        Db::startTrans();
        try{
            $field = 'goods_id,num,attr_id';
            $details = Db::table('up_self_order_detail')
                ->where('order_id',$order_id)
                ->field($field)
                ->select();
            foreach ($details as $k=>$v){
                if($contract == 1){
                    //1、加上商品的库存
                    Db::table('up_self_goods')->where('good_id',$v['goods_id'])->setInc('good_stock',$v['num']);
                    //2、加上attr的库存
                    Db::table('up_self_goods_attr')->where('attr_id',$v['attr_id'])->setInc('stock',$v['num']);
                }
            }
            //3、改变订单状态
            Db::table('up_self_order')->where('order_id',$order_id)->setField('is_pay',2);
            Db::commit();
            return json(['status'=>200,'msg'=>'操作成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 支付完取消订单
     *
     */
    public function canclePayOrder()
    {
        extract(input());
        $order = Db::table('up_self_order')->where('order_id', $order_id)
            ->field('is_pay,order_contract,is_send,order_cancel_status,order_push_erp')->find();
//         && $order['order_push_erp'] == 1
        if($order['is_pay'] == 1 && $order['order_contract'] == 2 && $order['is_send'] == 0 && $order['order_cancel_status'] <= 2){
            $res = Db::table('up_self_order')->where('order_id',$order_id)->setField('order_cancel_status',4);
            if($res){
                return json_encode(['status'=>200,'msg'=>'取消成功']);
            }else{
                return json_encode(['status'=>0,'msg'=>'取消失败，请刷新重试']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'只有已支付且未发货未取消过的的订单才可以取消']);
        }
    }
    /**
     * 确认收货
     */
    public function receiptMyOrder()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $is_send = Db::table('up_self_order')->where('order_id', $order_id)->value('is_send');
        if($is_send != 1){
            return json_encode(['status'=>0,'msg'=>'只有待收货订单才可以确认收货']);
        }
        $update = [
            'is_send' => 2,
            'confirm_time' => $today
        ];
        $res = Db::table('up_self_order')->where('order_id', $order_id)->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 删除订单：只有已取消的才可以删除订单
     */
    public function delMyOrder()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $is_pay = Db::table('up_self_order')->where('order_id', $order_id)->value('is_pay');
        if($is_pay != 2){
            return json_encode(['status'=>0,'msg'=>'只有已取消的订单才可以删除']);
        }
        $update = [
            'is_delete' => 1,
            'deleted_at' => $today
        ];
        $res = Db::table('up_self_order')->where('order_id', $order_id)->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 评价我的订单：特殊符号作为分隔符’__‘
     */
    public function orderComment()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $is_send = Db::table('up_self_order')->where('order_id', $order_id)->value('is_send');
        if($is_send != 2){
            return json_encode(['status'=>0,'msg'=>'只有待评价订单才可以评价']);
        }
        $comments = json_decode($comments,true);
        //
        $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
        $good_table = 'up_self_goods';
        $goods_comment_table = 'up_self_goods_comment';
        if($contract != 1){
            $good_table = 'up_goods';
            $goods_comment_table = 'up_goods_comment';
        }
        //
        Db::startTrans();
        try{
            foreach ($comments as $k=>$vv){
                $det = Db::table('up_self_order_detail')->where('detail_id', $vv['detail_ids'])->field('goods_id,goods_info')->find();
                $v = $det['goods_id'];
                //1、重新算好评率
                $good = Db::table($good_table)->where('good_id',$v)->field('good_score,good_comment')->find();
                $allscore = ($good['good_score'] * $good['good_comment']) + ($vv['scores'] * 20);
                $nowscore = round($allscore/($good['good_comment']+1),1);
                Db::table($good_table)->where('good_id',$v)->setField('good_score',$nowscore);
                //2、评论数加1
                Db::table($good_table)->where('good_id',$v)->setInc('good_comment',1);
                //3、入评论表
                $comment = [
                    'comment_order_id' => $order_id,
                    'comment_type' => $contract,
                    'comment_good_id' => $v,
                    'comment_detail_id' => $vv['detail_ids'],
                    'comment_content' => $vv['contents'],
                    'comment_image' => trim($vv['pics'],','),
                    'comment_guige' => $det['goods_info'],
                    'comment_star' => $vv['scores'],
                    'comment_user_id' => $user_id,
                    'comment_time' => $today
                ];
                Db::table($goods_comment_table)->insert($comment);
            }
            //4、改变订单状态(已评论)
            Db::table('up_self_order')->where('order_id',$order_id)->setField('is_send',3);
            Db::commit();
            return json(['status'=>200,'msg'=>'操作成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }

    /**
     * 查看评价
     * @return \think\response\Json
     */
    public function seeOrderComment()
    {
        extract(input());
        $is_send = Db::table('up_self_order')->where('order_id', $order_id)->value('is_send');
        if($is_send != 3){
            return json_encode(['status'=>0,'msg'=>'只有已评价订单才可以查看']);
        }
        //
        $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
        $good_table = 'up_self_goods';
        $goods_comment_table = 'up_self_goods_comment';
        if($contract != 1){
            $good_table = 'up_goods';
            $goods_comment_table = 'up_goods_comment';
        }
        //
        $field = 'num,unit_price,goods_info,good_name,good_thumb';
        $field .= ',comment_content,comment_image,comment_star';
        $comments = Db::table($goods_comment_table)->alias('c')
            ->join("$good_table g",'c.comment_good_id=g.good_id','LEFT')
            ->join('up_self_order_detail od','c.comment_detail_id=od.detail_id','LEFT')
            ->where('comment_order_id',$order_id)
            ->where('comment_type',$contract)
            ->field($field)
            ->select();
        foreach ($comments as $k=>$v){
            if($v['comment_image']){
                $comments[$k]['comment_image'] = explode(',',$v['comment_image']);
            }
        }
        return json(['status'=>200,'msg'=>$comments]);
    }
    /**
     * 退货原因
     */
    public function tuiReason()
    {
        extract(input());
        $res = Db::table('up_return')->select();
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * 申请售后：只有已发货后的才可以
     * 后台说明：TODO：
     *          1、如果订单1件商品：同意或拒绝则tui_status已完成
     *          2、如为多件，sale_status为1时同意或拒绝则tui_status已完成
     */
    public function afterSaleOrder()
    {
        extract(input());
//        $detail_ids='433';$order_id=452;$type=1;$newsizes='100';$user_id=200;$remark='';$express='';$express_no='';
        $today = date('Y-m-d H:i:s');
        $is_send = Db::table('up_self_order')->where('order_id', $order_id)->value('is_send');
        if ($is_send < 2) {
            return json_encode(['status' => 0, 'msg' => '只有已收货订单才可以申请售后']);
        }
        $detail_ids = explode(',', trim($detail_ids, ','));
        //
        $oson = Db::table('up_self_order')->where('order_id', $order_id)
            ->field('order_contract,order_user_son_id')->find();
        $contract = $oson['order_contract'];
        $good_table = 'up_self_goods';
        $goods_comment_table = 'up_self_goods_comment';
        $tui_user_son_id = 0;
        if($contract != 1){
            $good_table = 'up_goods';
            $goods_comment_table = 'up_goods_comment';
            $sondata = Db::table('up_u_user_son')->where('uson_id',$oson['order_user_son_id'])
                ->field('uson_id,uson_username,user_gender,uson_year,uson_school,uson_idcard,uson_size')
                ->find();
            if(empty($sondata)){
                return json(['status' => 0, 'msg' => '学生信息有误，请重新选择学生']);
            }
            $tui_user_son_id = $sondata['uson_id'];
        }
        //
        Db::startTrans();
        try {
            if($contract != 1 && $type == 1) {
                $newsizes = explode(',', trim($newsizes, ','));
                if (count($newsizes) != count($detail_ids)) {
                    return json_encode(['status' => 0, 'msg' => '请选择要换货的尺寸,每个都要选哦']);
                }
            }
            foreach ($detail_ids as $k => $v) {
                //1、入售后表：
                $number = time() . rand(100000, 999999) . $k;
                $tui = [
                    'user_id' => $user_id,
                    'tui_type' => $contract,
                    'tui_user_son_id' => $tui_user_son_id,
                    'order_id' => $order_id,
                    'order_detail_id' => $v,
                    'order_no' => $number,
                    'order_erp_wl_no' => 'app' . $number,
                    'type' => $type,//1换货 2退款
                    'refund_price' => 0,
                    'remark' => $remark,
                    'express' => $express,
                    'express_no' => $express_no,
                    'created_at' => $today
                ];
                $suan = Db::table('up_self_order_detail')->where('detail_id', $v)->field('th_status,num,unit_price')->find();
                if($suan['th_status'] != 0){
                    Db::rollback();
                    return json(['status' => 0, 'msg' => '已经有重复的售后数据了，请重新选择']);
                }
                if($type == 2){ //如果是退款的话退多少
                    $refund_price = $suan['num'] * $suan['unit_price'];
                    $tui['refund_num'] = $suan['num'];
                    $tui['refund_price'] = $refund_price;
                    $tui['should_money'] = $refund_price;
                }
                //>>>>>>>>>>>>>>>>>>>获取唯一编码start>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                if($contract != 1 && $type == 1) {
                    $old = Db::table('up_self_order_detail')
                        ->where('detail_id', $v)
                        ->field('attr_id,goods_id,num,goods_coding_unique,pay_year')
                        ->find();
                    $tui['erp_new_size'] = $old['attr_id'];
                    $tui['erp_huan_uninumber'] = $old['goods_coding_unique'];
                    $newsizes[$k] = (int)$newsizes[$k];
                    if(empty($newsizes[$k]) || $newsizes[$k] <= 0){
                        Db::rollback();
                        return json(['status' => 0, 'msg' => '请选择要调换的尺码']);
                    }
                    if ($newsizes[$k] != $old['attr_id']) {
                        $o_g = Db::table('up_goods')
                            ->where('good_id', $old['goods_id'])
                            ->field("good_name,good_color,good_coding_less")
                            ->find();
                        $less_code = Db::table('up_good_spec')
                            ->where('spec_good_coding_less', $o_g['good_coding_less'])
                            ->where('spec_size', $newsizes[$k])
                            ->where('spec_size_q', 2)
                            ->value('spec_good_coding_less');
                        if ($less_code) { //说明此款号有Q款，再去判断
                            $erp = 2;
                        } else {
                            $erp = 1;//压根没有Q款
                        }
                        $sure = $this->getStudentGoods($sondata['uson_school'], $old['pay_year'], $sondata['user_gender'], $erp, $o_g['good_coding_less']);
                        $size_code = Db::table('up_good_spec')
                            ->where('spec_good_coding_less', $o_g['good_coding_less'])
                            ->where('spec_size', $newsizes[$k])
                            ->where('spec_size_q', $sure['sg_good_q'])
                            ->value('spec_size_two');
                        if(empty($size_code)){
                            Db::rollback();
                            return json_encode(['status'=>0,'msg'=>'尺码有误，请刷新重试，或重新选择尺码~']);
                        }
                        $unique_code = $sure['sg_good_coding'] . $size_code;
                        if ($sure['sg_sign']) {
                            $unique_code .= $sure['sg_sign'];
                        }
                        $tui['erp_new_size'] = $newsizes[$k];
                        $tui['erp_huan_uninumber'] = $unique_code;
                        //年份和交期
                        $time = time();
                        $days = Db::table('up_about')->where('id',10)->value('content');
                        $days = (int)$days;
                        $days_after = date("Ymd",($time + 3600*$days*24));
                        $tui['erp_year'] = $sure['sg_year'];
                        $tui['erp_done'] = $days_after;
                    }
                }
                //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<获取唯一编码end<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//                dump($tui);die;
                Db::table('up_self_order_tui')->insert($tui);
            }
            //2、改详情表
            Db::table('up_self_order_detail')->where('detail_id', 'in',$detail_ids)->update([
                'refund_status' => 1,
                'th_status' => $type,
            ]);
            //3、改order表售后状态
            $goodsnum = Db::table('up_self_order_detail')->where('order_id', $order_id)->count();
            if($goodsnum > 1){ //超出一件：全售后则order为售后中，否则不改
                $goods_errornum = Db::table('up_self_order_detail')
                    ->where('order_id', $order_id)
                    ->where('th_status', '>',0)
                    ->count();
                if($goodsnum == $goods_errornum){
                    Db::table('up_self_order')->where('order_id', $order_id)->update([
                        'sale_status' => 1,
                        'tui_status' => 0,
                    ]);
                }
            }else{ //只一件：detail售后状态order售后状态
                Db::table('up_self_order')->where('order_id', $order_id)->update([
                    'sale_status' => $type+1,
                    'tui_status' => 0,
                ]);
            }
            Db::commit();
            $title = '退换货通知';
            $content = '发起退换货后，我们将在收货后进行核实，并与您联系';
            allInNotice($title,$content,3,$user_id,$order_id,$contract);
            try{
                $this->Jpush(1, $user_id, '发起售后通知', ['n_id' => $order_id,'type' => $contract,'n_type' => 3]);
            }catch(\Exception $e){

            }
            return json(['status' => 200, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败，请刷新重试']);
        }
    }

    /**
     * 查看退货商品的详情
     * @return \think\response\Json
     */
    public function getTuiInfo()
    {
        extract(input());
        //
        $order_id = Db::table('up_self_order_detail')->where('detail_id', $detail_id)->value('order_id');
        $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
        $good_table = 'up_self_goods';
        if($contract != 1){
            $good_table = 'up_goods';
        }
        //typeorder_no
        $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,th_status,refund_status';
        $field .= ',remark,merchant_remark,t.created_at,order_erp_wl_no order_no,status,express,express_no,merchant_express,merchant_express_no';
        $data = Db::table('up_self_order_tui')->alias('t')
            ->join('up_self_order_detail od','t.order_detail_id=od.detail_id','LEFT')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where('order_detail_id', $detail_id)
            ->order('created_at desc')
            ->field($field)
            ->find();
        return json(['status' => 200, 'msg' =>$data]);
    }
    /**
     * 开发票
     * @return \think\response\Json
     */
    public function fapiaoOrder()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $is_send = Db::table('up_self_order')->where('order_id', $order_id)
            ->field('is_send,fapiao_status,fapiao_head,order_contract,order_user_son_id,sale_status')->find();
        if ($is_send['is_send'] < 2) {
            return json_encode(['status' => 0, 'msg' => '只有已收货订单才可以开具发票']);
        }
        if ($is_send['fapiao_status'] != 0) {
            if(empty($is_send['fapiao_head'])){
                return json_encode(['status' => 0, 'msg' => '您已经开过发票了']);
            }else{
                return json_encode(['status' => 0, 'msg' => '此单不具备开发票条件']);
            }
        }
        //
        $shouhou_habe = Db::table('up_self_order_detail')
            ->where('order_id', $order_id)
            ->where('th_status', '<>',0)
            ->where('refund_status', '<>',2)
            ->find();
        if ($shouhou_habe) {
            return json_encode(['status' => 0, 'msg' => '此订单有进行中的售后，暂不能开票']);
        }
        $detailids = Db::table('up_self_order_detail')->where('order_id', $order_id)->column('detail_id');
        $detailids_no = Db::table('up_self_order_tui')
            ->where('order_detail_id', 'in',$detailids)
            ->where('status', 2)
            ->column('order_detail_id');
        $where = [
            'order_id' => $order_id
        ];
        if($detailids_no){
            $where['detail_id'] = ['not in',$detailids_no];
        }
        $details = Db::table('up_self_order_detail')
            ->where($where)
            ->field('detail_id,num,unit_price')
            ->select();
        if(empty($details)){
            return json_encode(['status' => 0, 'msg' => '此订单已经售后，不能开票']);
        }
        $mingxi = [];
        foreach ($details as $k=>$v){
            $mingxi[] = [
                'goodsname' => '学生校服',
                'num' => $v['num'],
                'price' => $v['unit_price'],
                'unit' => '套',
                'hsbz' => '1',
                'taxrate' => '0.13',
                'spbm' => '104020199',
                'fphxz' => '0',
            ];
        }
        //
        if($is_send['order_contract'] != 1){
            $schid = Db::table('up_u_user_son')->where('uson_id',$is_send['order_user_son_id'])
                ->value('uson_school');
            if(empty($schid)){
                return json(['status' => 0, 'msg' => '学生信息有误，无法开票']);
            }
            $sch = Db::table('up_school')->where('school_id',$schid)
                ->field('school_head,school_shui')->find();
            if(empty($sch)){
                return json(['status' => 0, 'msg' => '学校信息有误，无法开票']);
            }
            if(empty($sch['school_head']) || empty($sch['school_shui'])){
                return json(['status' => 0, 'msg' => '学校信息不全，请稍后再开票']);
            }
            $fapiao = [
                'fapiao_status' => 1,
                'fapiao_type' => 2,
                'fapiao_head' => $sch['school_head'],
                'fapiao_shui' => $sch['school_shui'],
                'fapiao_email' => $fapiao_email,
                'fapiao_remark' => $fapiao_remark,
                'fapiao_time' => $today
            ];
        }else{
            $fapiao = [
                'fapiao_status' => 1,
                'fapiao_type' => $fapiao_type,
                'fapiao_head' => $fapiao_head,
                'fapiao_shui' => '',
                'fapiao_email' => $fapiao_email,
                'fapiao_remark' => $fapiao_remark,
                'fapiao_time' => $today
            ];
            if($fapiao_type == 2 ){
                $fapiao['fapiao_shui'] = $fapiao_shui;
            }
        }
        $user = Db::table('up_u_user')->where('user_id', $user_id)
            ->field('user_phone')->find();
        $res = $this->askFapiao($fapiao['fapiao_head'],$fapiao['fapiao_shui'],$user['user_phone'],$fapiao_email,$mingxi);
        if($res['status'] == 200){
            $fapiao['fapiao_ordernum'] = $res['msg'];
            Db::table('up_self_order')
                ->where('order_id', $order_id)
                ->update($fapiao);
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }

    /**
     * 通过单号获取物流信息
     * @return \think\response\Json
     */
    public function wuliuByNumber()
    {
        extract(input());
        $wldata = orderWuLiu($number);
        $msg = $wldata['msg'];
        if($wldata['status'] != 200){
            $wldata['msg'] = [];
        }
        return json(['status'=>$wldata['status'],'msg'=>$msg,'wldata'=>$wldata]);
    }
}